package org.artifact.core.util;

import org.artifact.core.constant.ArtifactErrorCode;
import org.artifact.core.exception.AbstractLogicException;
import org.artifact.core.exception.LogicDevException;
import org.artifact.core.exception.LogicProException;
import org.artifact.core.server.ServerContext;

import java.util.function.Consumer;

/**
 * @author : DengYing
 * @CreateDate : 2017年7月28日 下午5:44:31
 * @Description ：逻辑异常工具类
 */
public class LogicUtil{

	public static AbstractLogicException error(final int errorCode) {
		if (ServerContext.me().isDebug())
			return new LogicDevException(errorCode);
		else
			return new LogicProException(errorCode);
	}

	public static AbstractLogicException error(final int errorCode, final String message) {
		if (ServerContext.me().isDebug())
			return new LogicDevException(errorCode, message);
		else
			return new LogicProException(errorCode, message);
	}

	public static void isTrue(final int errorCode, final String message, final boolean bool) {
		if (bool) {
			throw error(errorCode, message);
		}
	}

	public static void isTrue(final int errorCode, final boolean bool) {
		if (bool) {
			throw error(errorCode);
		}
	}
	
	public static int getErrorCode(Throwable exception,Consumer<Throwable> consumer) {
		if (exception instanceof AbstractLogicException) {
			return ((AbstractLogicException) exception).getCode();
        } else {
			if (consumer!=null) {
				consumer.accept(exception);
			}
            return ArtifactErrorCode.UNKNOWN_ERROR;
        }		
	}
}
